import json
import os
from typing import Dict, Any


def ensure_dir(path: str) -> None:
    if not os.path.exists(path):
        os.makedirs(path, exist_ok=True)


def save_metadata(root: str, name: str, version: str, path: str, metrics: Dict[str, Any]) -> str:
    ensure_dir(root)
    meta_path = os.path.join(root, "registry.json")
    data: Dict[str, Any] = {}
    if os.path.exists(meta_path):
        try:
            with open(meta_path, "r", encoding="utf-8") as f:
                data = json.load(f)
        except Exception:
            data = {}
    item = {"name": name, "version": version, "path": path, "metrics": metrics}
    data.setdefault("models", []).append(item)
    with open(meta_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    return meta_path